//
//  XJStatusDAL.swift
//  新浪微博
//
//  Created by 徐绩 on 16/5/3.
//  Copyright © 2016年 ayumi. All rights reserved.
//

import UIKit

private let MaxCacheTimeinterval: NSTimeInterval = 60 * 60 * 24 * 7

class XJStatusDAL: NSObject {
    
    ///检查本地是否有数据
    class func checkCacheData(max_id: Int64, since_id: Int64) -> [[String: AnyObject]]? {
        guard let uid = XJUserAccountModel.sharedModel.account?.uid else{
            return nil
        }
        var sql = "select statusid,status,uid from T_Status  \n"
        
        if max_id > 0{
            sql += "where statusid <= \(max_id) \n"
        }else{
            sql += "where statusid > \(since_id) \n"
            
        }
        // 添加UID的判断
        sql += "AND uid = \(uid) \n"
        
        // 排序
        sql += "ORDER BY statusid DESC \n"
        
        // 一页请求20个
        sql += "LIMIT 20"
        
        //执行语句
        let res = XJSQLiteManager.sharedManager.execRecordSet(sql)
        
        var result = [[String: AnyObject]]()
        
        //取出数据库数据反序列化
        for value in res {
            
            let dict = try! NSJSONSerialization.JSONObjectWithData(value["status"] as! NSData, options: []) as! [String :AnyObject]
            result.append(dict)
        }
        return result
    }
    
    ///加载数据
    class func loadData(max_id: Int64, since_id: Int64, completion:(dicts: [[String: AnyObject]]?)->()) {
        
        //判断本地是否有数据
        if let result = self.checkCacheData(max_id, since_id: since_id) where result.count > 0{
            
            //有就直接获取
            completion(dicts: result)
            return
        }
        //没有就去网络请求
        let url = "https://api.weibo.com/2/statuses/home_timeline.json"
        let param = [
            
            "access_token": XJUserAccountModel.sharedModel.accessToken ?? "",
            "max_id": "\(max_id)",
            "since_id": "\(since_id)"
        ]
        
        //发送请求
        XJNetworkTools.sharedTools.request(.Get, url: url, parameters: param) { (responseObject, error) -> () in
            
            if error != nil {
                return
            }
            
            guard let responseDict = responseObject as? [String: AnyObject] else {
                print("返回数据不是字典")
                //finished(isSuccess: false, count: 0)
                completion(dicts: nil)
                return
            }
            // 1. 取出 statuses 对应该节点的数据 （字典数组）
            guard let dicts = responseDict["statuses"] as? [[String: AnyObject]] else {
                //finished(isSuccess: false, count: 0)
                completion(dicts: nil)
                return
            }
            //保存从网络获取的数据
            XJStatusDAL.cacheData(dicts)
            //回调
            completion(dicts: dicts)
            
        }
    }
    
    ///保存从网络获取的数据
    class func cacheData(datas: [[String: AnyObject]]) {
        
        guard let uid = XJUserAccountModel.sharedModel.account?.uid else{
            return
        }
        //定义sql语句
        let sql = "INSERT INTO T_Status (statusid, status, uid) VALUES (?, ?, ?)"
        
        //执行sql语句保存数据
        XJSQLiteManager.sharedManager.queue.inTransaction { (db, rollback) -> Void in
            
            for value in datas {
            
                //微博id
                let statusid = value["id"]!
                
                //微博内容
                let status = try! NSJSONSerialization.dataWithJSONObject(value, options: [])
                
                if db.executeUpdate(sql, withArgumentsInArray: [statusid, status, uid]){
                    print("保存成功")
                }else{
                    print("保存失败")
                    rollback.memory = true
                }
            }
        }
    }
    
    ///清除缓存
    class func clearCache() {
        
        //距离当前时间前7天
        let targetDate = NSDate(timeIntervalSinceNow: -MaxCacheTimeinterval)
        
        let fm = NSDateFormatter()
        fm.locale = NSLocale(localeIdentifier:"en")
        fm.dateFormat = "yyyy-MM-dd HH:mm:ss"
        let targetDateStr = fm.stringFromDate(targetDate)
        
        let sql = "delete from T_Status where datetime < '\(targetDateStr)'"
        
        XJSQLiteManager.sharedManager.queue.inDatabase { (db) -> Void in
            
            if db.executeUpdate(sql, withArgumentsInArray: nil){
                print("删除成功")
            }else{
                print("删除失败")
                
            }
        }
    }
}






